package com.sx.zongzhi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sx.zongzhi.BaseActivity;
import com.sx.zongzhi.R;
import com.sx.zongzhi.adapter.PopMoveAdapter;
import com.sx.zongzhi.bean.MsgEvent;
import com.sx.zongzhi.bean.OrganizingBean;
import com.sx.zongzhi.bean.PopulationMoveBean;
import com.sx.zongzhi.bean.PopulationMoveSearchBean;
import com.sx.zongzhi.bean.UserBean;
import com.sx.zongzhi.presenter.PopMovePest;
import com.sx.zongzhi.utils.AppConstants;
import com.sx.zongzhi.utils.Global;
import com.sx.zongzhi.utils.MyRxBus;
import com.sx.zongzhi.utils.ToastUtils;
import com.sx.zongzhi.view.IPopMoveView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import xiaofei.library.datastorage.DataStorageFactory;
import xiaofei.library.datastorage.IDataStorage;

/**
 * 流动人口
 */
public class MovePopulationActivity extends BaseActivity implements
        SwipeRefreshLayout.OnRefreshListener , IPopMoveView{

    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_Total)
    TextView tv_Total;
    @BindView(R.id.imvAdd)
    ImageView imvAdd;
    private PopMoveAdapter popMoveAdapter;
    private List<PopulationMoveBean.RowsBean> moveBeans=new ArrayList<>();
    private int currentPager=1;
    private String orgId="";
    private boolean isGrid;
    private PopulationMoveBean.PermissionBean permissionBean;
    private PopMovePest movePest;
    private Disposable disposable;
    private PopulationMoveSearchBean searchBean;

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_household);
        ButterKnife.bind(this);
        setTitleName("流动人口");
        setRightImage(R.mipmap.icon_nav_search);
        imvAdd.setVisibility(View.GONE);
        movePest=new PopMovePest(this);
        initViews();
        onRefresh();
    }

    private void initViews() {
        IDataStorage dataStorage=DataStorageFactory.getInstance(
                getApplicationContext(),
                DataStorageFactory.TYPE_DATABASE);
        UserBean userBean=dataStorage.load(UserBean.class,getPackageName());
        orgId=userBean.getOrg().getId();
        if ("片组片格".equals(userBean.getOrg().getOrgLevel().getDisplayName())){//只有网格员可以添加
            isGrid=true;
        }else {
            isGrid=false;
            setRightImage2(R.mipmap.icon_nav_position);
        }
       
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setColorSchemeResources(AppConstants.colors);
            swipeRefreshLayout.setOnRefreshListener(this);
        }
        recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        popMoveAdapter = new PopMoveAdapter(this,R.layout.item_household_list,moveBeans);
        popMoveAdapter.setEmptyView(View.inflate(this,R.layout.load_error_view,null));
        recyclerView.setAdapter(popMoveAdapter);
        popMoveAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                currentPager++;
                loadData();
            }
        },recyclerView);

        popMoveAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(MovePopulationActivity.this,MovePopulationDetailActivity.class)
                .putExtra("PopulationId",moveBeans.get(position).getId())
                        .putExtra("PermissionBean",permissionBean)
                        .putExtra("orgId",orgId));
            }
        });
        //订阅筛选组织机构
        disposable= MyRxBus.get().toObservable(MsgEvent.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<MsgEvent>() {
                    @Override
                    public void accept(MsgEvent bean) throws Exception {
                        if ("MovePopulationActivity".equals(bean.getRequest())) {
                            if (bean.getType()==0) {
                                OrganizingBean  oBean = (OrganizingBean) bean.getMsg();
                                if (oBean != null) {
                                    currentPager = 1;
                                    orgId = oBean.getId();
                                    if (permissionBean!=null&&permissionBean.isAddFloatingPopulation()&&oBean.isGrid()){
                                        imvAdd.setVisibility(View.VISIBLE);
                                    }else {
                                        imvAdd.setVisibility(View.GONE);
                                    }
                                    onRefresh();
                                }
                            }else if (bean.getType()==1){//查询
                                searchBean= (PopulationMoveSearchBean) bean.getMsg();
                                currentPager=1;
                                loadData();
                            }else if(bean.getType()==2){
                                onRefresh();
                            }
                        }
                    }
                });
    }


    @OnClick({R.id.imv_Right,R.id.imv_Right2, R.id.imvAdd})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.imv_Right://搜索
                startActivity(new Intent(this,MovePopulationSearchActivity.class));
                break;
            case R.id.imv_Right2://位置
                startActivity(new Intent(this,OrganizingActivity.class).
                        putExtra(Global.ACTIVITY_FRAGMENT,"MovePopulationActivity"));
                break;
            case R.id.imvAdd://添加
                startActivity(new Intent(this,AddMovePopulationActivity.class)
                        .putExtra("orgId",orgId)
                        .putExtra("isEdit",false));
                break;
        }
    }

    @Override
    public void onRefresh() {
        currentPager=1;
        searchBean=null;
        loadData();
    }

    @Override
    protected void onDestroy() {
        if (disposable!=null){
            disposable.dispose();
        }
        super.onDestroy();
    }

    private void loadData() {
        movePest.getPopMoveList(orgId,searchBean,currentPager,15);
    }

    @Override
    public void getPopMoveList(PopulationMoveBean moveBean) {
        swipeRefreshLayout.setRefreshing(false);
        if (moveBean.getPermission()!=null&&permissionBean==null){
            permissionBean=moveBean.getPermission();
            if (isGrid&&permissionBean.isAddFloatingPopulation()){
                imvAdd.setVisibility(View.VISIBLE);
            }else {
                imvAdd.setVisibility(View.GONE);
            }
        }
        if (currentPager==1){
            moveBeans.clear();
            popMoveAdapter.setNewData(moveBeans);
        }
        if (moveBean.getRows()!=null){
            moveBeans.addAll(moveBean.getRows());
        }
        popMoveAdapter.notifyDataSetChanged();
        if (moveBeans.size()>=moveBean.getRecords()){
            popMoveAdapter.loadMoreEnd();
        }else {
            popMoveAdapter.loadMoreComplete();
        }
        tv_Total.setText("共"+moveBean.getTotal()+"条数据");
    }

    @Override
    public void showError(String message) {
        swipeRefreshLayout.setRefreshing(false);
        ToastUtils.showToast(this,message);
    }
}
